package com.mayikt.log.consumer;

import com.alibaba.fastjson.JSON;
import com.mayikt.log.entity.ErrorLogEntity;
import com.mayikt.log.entity.SenderContactsEntity;
import com.mayikt.log.feign.WeiXinErrorTemplateServiceFeign;
import com.mayikt.log.mapper.ErrorLogMapper;
import com.mayikt.log.mapper.SenderContactsMapper;
import com.mayikt.request.ErrorTemplateDto;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class LogConsumer {

    @Autowired
    private ErrorLogMapper errorLogMapper;
    @Autowired
    private WeiXinErrorTemplateServiceFeign weiXinErrorTemplateServiceFeign;
    @Autowired
    private SenderContactsMapper senderContactsMapper;

    @KafkaListener(topics = "mayikt-topic-log")
    public void receive(ConsumerRecord<?, ?> consumer) throws Exception {
        String json = (String) consumer.value();
        if (StringUtils.isEmpty(json)) {
            return;
        }
        // 存放到数据库或者es、mongdb中
        ErrorLogEntity errorLogEntity = JSON.parseObject(json, ErrorLogEntity.class);
//        String messageId = errorLogEntity.getMessageId();
        // 根据消息的全局id主动查询 ，如果在数据库存在的情况下 不会执行以下流程
        // 插入到数据库中
        try {
            int result = errorLogMapper.insertErrorLog(errorLogEntity);
            if (result <= 0) {
                throw new Exception("日志插入数据库失败,开始触发MQ重试策略");

            }
            List<SenderContactsEntity> openIdList = senderContactsMapper.getSenderContactsOpenId();
            for (SenderContactsEntity sd :
                    openIdList) {
                // 调用微信服务接口 发送消息模板
                String serviceId = errorLogEntity.getServiceId();
                Date createTime = errorLogEntity.getCreateTime();
                String errorMsg = errorLogEntity.getClassName() + "的" + errorLogEntity.getMethodName() + "方法," + errorLogEntity.getLineNumber()
                        + "行" + "出现了" + errorLogEntity.getErrorContent() + "异常";
                ErrorTemplateDto errorTemplateDto =
                        new ErrorTemplateDto(serviceId, createTime, errorMsg, errorLogEntity.getServerIp(), sd.getOpenId());
                weiXinErrorTemplateServiceFeign.sendErrorTemplate(errorTemplateDto);
            }
            return;

        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }
}